import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'

class crud {
  constructor() {
  }

  async table(fn, params) {
    const loading = ref(false)
    const tableData = ref([])
    const tableTotal = ref(0)
    const currPage = ref(1)
    const limit = ref(10)

    const loadData = async (page) => {
      loading.value = true
      params.value.page = page
      params.value.limit = limit.value
      console.info(params)
      const { data, current_page, total } = await fn(params)
      console.info({ data, current_page, total })
      tableData.value = data
      currPage.value = current_page
      tableTotal.value = total || data.length
      loading.value = false
    }

    onMounted(async () => {
      await loadData(currPage.value)
    })

    watch([currPage, limit], () => {
      loadData(currPage.value)
    })

    return { loading, tableData, tableTotal, currPage, limit, loadData }
  }

  async info(fn, id) {
    return await fn(id)
  }

  async update(fn, row, reload) {
    await fn(row.id || 0, row) && await reload()
    this.successful()
  }

  async delete(fn, row, selects, reload) {
    let ids = row.hasOwnProperty('id') ? [row.id] : selects.map((i) => i.id)
    if (ids.length === 0) {
      this.fail('请选择操作项')
      return false
    }
    await fn(ids.toString()) && await reload()
    this.successful()
  }

  dialog(ref, id) {
    ref.value.open(id)
  }

  successful(message = '操作成功') {
    ElMessage.success(message)
  }

  fail(message = '操作失败') {
    ElMessage.error(message)
  }
}

export default new crud()
